package com.augmentum.oes.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;

import com.augmentum.oes.model.Pagination;
import com.augmentum.oes.model.Question;
import com.augmentum.oes.util.JDBCUtil;
import com.augmentum.oes.dao.BaseDao;
import com.augmentum.oes.dao.QuestionDao;

public class QuestionDaoImpl extends BaseDao implements QuestionDao {

    @Override
    public void createQuestion(Question question) {
        saveAll(question);
    }

    @Override
    public List<Question> queryAllQuestion() {
        String sql = "SELECT * FROM question WHERE question_status=1";
        return jdbcTemplate.query(sql, new QRowMapper());
    }

    @Override
    public Question queryById(int id) {
        String sql = "SELECT * FROM question WHERE id=? and question_status=1";
        return jdbcTemplate.queryForObject(sql, new QRowMapper(), id);
    }

    @Override
    public List<Question> queryQuestionPage(Pagination<Question> pagination) {
        String order;
        int orderIndex = pagination.getOrder();
        switch (orderIndex) {
        case 1:
            order = "id";
            break;
        case 2:
            order = "id DESC";
            break;
        default:
            order = "id";
            break;
        }
        String sql = "SELECT * FROM question WHERE question_status=1 AND (question_content LIKE '%"
                + pagination.getFuzzyWord() + "%' OR id LIKE '%" + pagination.getFuzzyWord() + "%') ORDER BY " + order
                + " LIMIT " + pagination.getOffset() + "," + pagination.getPageSize();
        return jdbcTemplate.query(sql, new QRowMapper());
    }

    @Override
    public void deleteQ(int id) {
        String sql = "UPDATE question SET question_status=0 WHERE id=?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public void updateQ(Question question) {
//        String sql = "UPDATE question SET question_content=?, answer_a=?, answer_b=?, answer_c=?, answer_d=?, correct_answer=? WHERE id="
//                + id;
//        jdbcTemplate.update(sql, obj);
    }

    public int getCount(String fuzzy) {
        String sql = "SELECT COUNT(*) FROM question WHERE question_status=1 AND question_content LIKE '%" + fuzzy
                + "%'";
        return jdbcTemplate.queryForInt(sql);
    }

    @Override
    public List<Question> randQ(int count) {
        String sql = "SELECT * FROM question ORDER BY RAND() LIMIT ?";
        return jdbcTemplate.query(sql, new QRowMapper(), count);
    }

    class QRowMapper implements RowMapper<Question> {
        @Override
        public Question mapRow(ResultSet rs, int arg1) throws SQLException {
            Question question = new Question();
            JDBCUtil.toBean(question, rs);
            return question;
        }
    }
}
